package com.cui.project.exception;

import com.api.common.alert.CommonAlertHelper;
import com.api.common.common.BaseResponse;
import com.api.common.common.ErrorCode;
import com.api.common.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 *
 * @author cui
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Resource
    private CommonAlertHelper alertHelper;

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("businessException: " + e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("runtimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }

    // ✅ 新增：处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> handleValidationExceptions(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        log.error("参数校验失败: {}", errors);
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, errors.toString());
    }

    // ✅ 新增：处理空指针异常
    @ExceptionHandler(NullPointerException.class)
    public BaseResponse<?> handleNullPointerException(NullPointerException e) {
        log.error("空指针异常", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统内部错误");
    }

    // ✅ 新增：处理所有未捕获异常
    @ExceptionHandler(Exception.class)
    public BaseResponse<?> handleException(Exception e) {
        log.error("未知异常", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统异常，请联系管理员");
    }


    // 可以在 GlobalExceptionHandler 中添加
    @ExceptionHandler(DataAccessException.class)
    public BaseResponse<?> handleDataAccessException(DataAccessException e) {
        log.error("数据库访问异常", e);

        // 发送告警给DBA团队
        alertHelper.databaseConnectionFailure(
                "main-datasource",
                e.getMessage()
//                "dba-team@example.com"
        );

        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "数据库异常");
    }
}